<script setup name="BizProductInfoIndex">
import eventBus from "@/utils/eventBus";
import { usePagination } from "@/utils/composables";
import FormMode from "./modules/FormMode/index.vue";
import {
  listRubbishTypeTree,
  getRubbishTypeList
} from "@/api/biz/bizRubbishType";
import { parseTime } from "@/utils/aidex";
import { updateBizProductInfoStatus } from "@/api/biz/bizProductInfo";
import {
  listBizProductInfo,
  delBizProductInfo,
  exportBizProductInfo
} from "@/api/biz/bizProductInfo";
const { pagination, getParams, onSizeChange, onCurrentChange, onSortChange } =
  usePagination();
const router = useRouter();

const data = ref({
  loading: false,
  /**
   * 详情展示模式
   * router 路由跳转
   * dialog 对话框
   * drawer 抽屉
   */
  formMode: "drawer",
  // 详情
  formModeProps: {
    visible: false,
    id: "",
    type: "0"
  },
  // 搜索
  search: {
    rubbishTypeId: "",
    type: "0",
    deptName: ""
  },
  // 批量操作
  batch: {
    enable: false,
    selectionDataList: []
  },
  // 列表数据
  dataList: [],
  // 分类
  rubbishTypeList: [],
  formatRubbishTypeList: []
});

// 页面挂载时 调用
onMounted(() => {
  getDataList();
  if (data.value.formMode === "router") {
    eventBus.on("get-data-list", () => {
      getDataList();
    });
  }
  listRubbishTypeTree("", 3, data.value.formModeProps.type).then((res) => {
    data.value.rubbishTypeList = res.data;
  });
  getRubbishTypeList().then((res) => {
    data.value.formatRubbishTypeList = res.data;
  });
});
//
onBeforeUnmount(() => {
  if (data.value.formMode === "router") {
    eventBus.off("get-data-list");
  }
});

function formatTypeName(typeId) {
  var name = "";
  data.value.formatRubbishTypeList.map((item) => {
    console.log(item.id, typeId);
    if (item.id == typeId) {
      name = item.deptName;
    }
  });
  return name;
}
function handShowIndexEdit(val, id) {
  console.log("xx:", val, id);
  var showIndex = 0;
  if (val) {
    showIndex = 0;
  } else {
    showIndex = 1;
  }
  var pro = { showIndex: showIndex, id: id };
  updateBizProductInfoStatus(pro).then((res) => {
    if (res.code == 200) {
      ElMessage.success({
        message: "修改成功",
        center: true
      });
    } else {
      ElMessage.error({ message: "修改失败", center: true });
    }
  });
}

function handStatusEdit(val, id) {
  console.log("xx:", val, id);
  var status = 0;
  if (val) {
    status = 0;
  } else {
    status = 1;
  }
  var pro = { status: status, id: id };
  updateBizProductInfoStatus(pro).then((res) => {
    if (res.code == 200) {
      ElMessage.success({
        message: "修改成功",
        center: true
      });
    } else {
      ElMessage.error({ message: "修改失败", center: true });
    }
  });
}
// 每页数量切换
function sizeChange(size) {
  onSizeChange(size).then(() => getDataList());
}

// 当前页码切换（翻页）
function currentChange(page = 1) {
  onCurrentChange(page).then(() => getDataList());
}

// 字段排序
function sortChange(prop, order) {
  onSortChange(prop, order).then(() => getDataList());
}
// 查询
function getDataList() {
  data.value.loading = true;
  let params = getParams();
  data.value.search.title && (params.title = data.value.search.title);
  data.value.search.fuTitle && (params.fuTitle = data.value.search.fuTitle);
  data.value.search.type && (params.type = data.value.search.type);
  data.value.search.rubbishTypeId &&
    (params.rubbishTypeId = data.value.search.rubbishTypeId);
  listBizProductInfo(params).then((res) => {
    data.value.loading = false;
    data.value.dataList = res.data.list.map((item) => {
      if (item.showIndex == 0) {
        item.showIndex = true;
      } else {
        item.showIndex = false;
      }
      if (item.status == 0) {
        item.status = true;
      } else {
        item.status = false;
      }
      item.indexImg = JSON.parse(item.indexImg);
      return item;
    });

    pagination.value.total = res.data.total;
  });
}

// 编辑
function onEdit(row) {
  data.value.formMode = "drawer";

  if (data.value.formMode === "router") {
    router.push({
      name: "routerName",
      params: {
        id: row.id
      }
    });
  } else {
    data.value.formModeProps.id = row.id;
    data.value.formModeProps.type = "0";
    data.value.formModeProps.visible = true;
  }
}
// 添加
function onAdd() {
  data.value.formModeProps.id = "";
  data.value.formModeProps.type = "0";
  data.value.formMode = "dialog";
  data.value.formModeProps.visible = true;
}
// 批量删除 单独删除
function onDel(row) {
  const ids =
    row.id ||
    data.value.batch.selectionDataList.map((item) => {
      return item.id;
    });
  const names =
    row.fuTitle ||
    data.value.batch.selectionDataList.map((item) => {
      return item.fuTitle;
    });
  if (ids.length > 0) {
    ElMessageBox.confirm("确认删除「" + names + "」吗？", "确认信息")
      .then(() => {
        delBizProductInfo(ids).then((res) => {
          getDataList();
          if (res.code == 200)
            ElMessage.success({
              message: "删除成功",
              center: true
            });
        });
      })
      .catch(() => {});
  } else {
    ElMessage.warning({ message: "请选择数据", center: true });
  }
}
</script>

<template>
  <div>
    <page-main style="height: calc(100vh - 160px); margin: 10px">
      <search-bar>
        <el-form
          :model="data.search"
          size="default"
          label-width="auto"
          label-suffix=""
        >
          <el-row :gutter="30">
            <el-col :span="5">
              <el-form-item label="产品分类">
                <el-tree-select
                  v-model="data.search.rubbishTypeId"
                  :data="data.rubbishTypeList"
                  :default-expand-all="true"
                  node-key="id"
                  :check-strictly="true"
                  style="width: 100%"
                  clearable
                />
              </el-form-item>
            </el-col>
            <el-col :span="5">
              <el-form-item label="产品标题">
                <el-input
                  v-model="data.search.title"
                  placeholder="请输入产品标题"
                  clearable
                  @keydown.enter="currentChange()"
                  @clear="currentChange()"
                />
              </el-form-item>
            </el-col>
            <el-col :span="5">
              <el-form-item label="副标题">
                <el-input
                  v-model="data.search.fuTitle"
                  placeholder="请输入产品标题"
                  clearable
                  @keydown.enter="currentChange()"
                  @clear="currentChange()"
                />
              </el-form-item>
            </el-col>

            <el-col :span="5">
              <el-form-item>
                <el-button type="primary" @click="currentChange()">
                  <template #icon>
                    <el-icon>
                      <svg-icon name="ep:search" />
                    </el-icon>
                  </template>
                  查询
                </el-button>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </search-bar>
      <el-row>
        <el-col :span="24" style="text-align: right">
          <el-button-group>
            <el-button type="primary" @click="onAdd">
              <template #icon>
                <el-icon>
                  <svg-icon name="ep:circle-plus" />
                </el-icon>
              </template>
              新增
            </el-button>
            <el-button type="danger" @click="onDel">
              <template #icon>
                <el-icon>
                  <svg-icon name="ep:close-bold" :size="20" />
                </el-icon>
              </template>
              删除
            </el-button>
          </el-button-group>
        </el-col>
      </el-row>
      <div style="height: calc(100vh - 380px); overflow-y: auto">
        <el-table
          ref="table"
          v-loading="data.loading"
          class="list-table"
          :data="data.dataList"
          border
          highlight-current-row
          row-key="id"
          @sort-change="sortChange"
          @selection-change="data.batch.selectionDataList = $event"
        >
          >
          <el-table-column type="selection" align="center" />
          <el-table-column
            type="index"
            align="center"
            label="序号"
            width="60"
          />

          <el-table-column
            prop="rubbishTypeId"
            label="产品分类"
            show-overflow-tooltip
            align="center"
            width="120px"
          >
            <template v-slot="scope">
              {{ formatTypeName(scope.row.rubbishTypeId) }}
            </template>
          </el-table-column>

          <el-table-column
            prop="title"
            label="产品标题"
            show-overflow-tooltip
            align="center"
            width="150px"
          >
            <template v-slot="scope">
              {{ scope.row.title }}
            </template>
          </el-table-column>
          <el-table-column
            prop="fuTitle"
            label="产品副标题"
            show-overflow-tooltip
            align="center"
            width="160px"
          >
            <template v-slot="scope">
              {{ scope.row.fuTitle }}
            </template>
          </el-table-column>
          <el-table-column
            prop="brand"
            label="简介"
            show-overflow-tooltip
            align="center"
            width="150px"
          >
            <template v-slot="scope">
              {{ scope.row.brand }}
            </template>
          </el-table-column>
          <el-table-column
            prop="indexImg"
            label="产品图片"
            align="center"
            width="420px"
          >
            <template v-slot="scope">
              <el-image
                style="width: 60px; height: 50px; margin: 2px"
                :src="item"
                :zoom-rate="1.2"
                :preview-src-list="scope.row.indexImg"
                fit="cover"
                v-for="(item, index) in scope.row.indexImg"
              />
            </template>
          </el-table-column>
          <el-table-column
            prop="outCount"
            label="已售数量"
            show-overflow-tooltip
            align="center"
            width="100px"
          >
            <template v-slot="scope">
              {{ scope.row.outCount }}
            </template>
          </el-table-column>
          <el-table-column
            prop="priceStart"
            label="起售价"
            show-overflow-tooltip
            align="right"
            width="100px"
          >
            <template v-slot="scope">
              ¥{{ parseFloat(scope.row.priceStart).toFixed(2) }}
            </template>
          </el-table-column>

          <el-table-column
            prop="status"
            label="首页显示"
            show-overflow-tooltip
            align="center"
            width="100px"
          >
            <template v-slot="scope">
              <el-switch
                v-model="scope.row.showIndex"
                inline-prompt
                active-text="是"
                inactive-text="否"
                @change="(val) => handShowIndexEdit(val, scope.row.id)"
              />
            </template>
          </el-table-column>
          <el-table-column
            prop="status"
            label="是否上架"
            show-overflow-tooltip
            align="center"
            width="100px"
          >
            <template v-slot="scope">
              <el-switch
                v-model="scope.row.status"
                inline-prompt
                active-text="是"
                inactive-text="否"
                @change="(val) => handStatusEdit(val, scope.row.id)"
              />
            </template>
          </el-table-column>
          <el-table-column
            prop="sort"
            label="排序(升序)"
            show-overflow-tooltip
            align="center"
            width="100px"
          >
            <template v-slot="scope">
              {{ scope.row.sort }}
            </template>
          </el-table-column>
          <!-- <el-table-column
            prop="createTime"
            label="创建时间"
            show-overflow-tooltip
            align="center"
            width="160px"
          >
            <template v-slot="scope">
              {{ scope.row.createTime }}
            </template>
          </el-table-column> -->

          <el-table-column
            label="操作"
            width="160px"
            align="center"
            fixed="right"
          >
            <template #default="scope">
              <el-button-group>
                <el-button
                  type="primary"
                  size="small"
                  text
                  @click="onEdit(scope.row)"
                >
                  <template #icon>
                    <el-icon>
                      <svg-icon name="ant-design:edit-filled" />
                    </el-icon>
                  </template>
                  修改</el-button
                >

                <el-button
                  type="danger"
                  text
                  size="small"
                  @click="onDel(scope.row)"
                >
                  <template #icon>
                    <el-icon>
                      <svg-icon name="ep:close-bold" />
                    </el-icon>
                  </template>
                  删除
                </el-button>
              </el-button-group>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <el-pagination
        :current-page="pagination.page"
        :total="pagination.total"
        :page-size="pagination.size"
        :page-sizes="pagination.sizes"
        :layout="pagination.layout"
        :hide-on-single-page="false"
        class="pagination"
        background
        @size-change="sizeChange"
        @current-change="currentChange"
      />
    </page-main>
    <FormMode
      v-if="['dialog', 'drawer'].includes(data.formMode)"
      :id="data.formModeProps.id"
      :type="data.formModeProps.type"
      v-model="data.formModeProps.visible"
      :mode="data.formMode"
      @success="getDataList"
    />
  </div>
</template>

<style lang="scss" scoped>
.el-pagination {
  display: flex;
  justify-content: center;
  align-items: center;
}
::v-deep .el-table .el-table__cell {
  //解决层级穿透 使得 子元素不与其产生新的层叠关系
  position: static;
}
</style>
